//
//  NetworkOperation.m
//  THiOSWeb
//
//  Created by 卢臻 on 13-10-14.
//  Copyright (c) 2013年 Dexterlirush. All rights reserved.
//

#import "NetworkOperation.h"
#import "AFNetworking.h"
#import "NSString+URLEncode.h"

@implementation NetworkOperation

+(NSDictionary*)getActivityDetail: (int) activityID
{
    NSError *error;
    //加载一个NSURL对象
    NSString *url = [NSString stringWithFormat:@"http://app.student.tsinghua.edu.cn/android?operate=0&content=2&id=%i", activityID];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    //NSString *temp = [weatherDic objectForKey:@"id"];

    return result;
}

+ (void)sendRequestWithHost:(NSString *)host parameters:(NSDictionary *)parameters completion:(RequestCompletionBlock)completion
{
    NSString *url = host;
    int i = 0;
    for (NSString *key in [parameters allKeys]) {
        NSString *param = [parameters[key] description];
        param = [param encodeURLwithEncoding:NSUTF8StringEncoding];
        if (i == 0) {
            url = [url stringByAppendingFormat:@"?%@=%@", key, param];
        }
        else
        {
            url = [url stringByAppendingFormat:@"&%@=%@", key, param];
        }
        i++;
    }
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        DebugLog(@"%@", JSON);
        completion(YES, nil, JSON);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        DebugLog(@"%@", error);
        DebugLog(@"%@", [[NSString alloc] initWithData:JSON encoding:NSUTF8StringEncoding]);
        completion(NO, error, JSON);
    }];
    [operation start];
}

@end
